package cn.com.nes.site.modules.opportuntiy;

import cn.com.nes.site.entity.em.crm.opportunity.OpportunityClassificationEnum;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 商务项目业务处理 构建工厂
 */
@Component
public class OpportunityHandleFactory implements ApplicationContextAware {

    private final Map<OpportunityClassificationEnum, OpportunityHandle> STRATEGY_MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OpportunityHandle> tempMap = applicationContext.getBeansOfType(OpportunityHandle.class);
        tempMap.values()
                .forEach(strategyService -> STRATEGY_MAP.put(strategyService.opportunityClassification(), strategyService));
    }


    // @Override
    // public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    //     Map<String, Object> tempMap = applicationContext.getBeansWithAnnotation(Component.class); // 修改为获取所有Component注解的bean
    //     tempMap.values().stream()
    //             .filter(AbstractCommonOpportunityHandle.class::isInstance) // 筛选出AbstractCommonOpportunityHandle的实例或其代理
    //             .map(AbstractCommonOpportunityHandle.class::cast) // 强制转换为AbstractCommonOpportunityHandle
    //             .forEach(strategyService -> {
    //                 OpportunityClassificationEnum classification = ((AbstractCommonOpportunityHandle) strategyService).opportunityClassification();
    //                 STRATEGY_MAP.put(classification, strategyService);
    //             });
    // }

    // 根据广告类型获取相应的策略类，保持不变
    public <T extends OpportunityHandle> OpportunityHandle getInstance(
            OpportunityClassificationEnum classificationEnum) {
        return ObjectUtil.isNull(classificationEnum) ? STRATEGY_MAP.get(OpportunityClassificationEnum.COMMON) : STRATEGY_MAP.get(classificationEnum);
    }

}
